//
//  FiltrateViewController.m
//  pmmSS
//
//  Created by Mac book on 2017/9/14.
//  Copyright © 2017年 WTFSSD. All rights reserved.
//

#import "FiltrateViewController.h"
#import "FiltratePriceAreaCell.h"
#import "FiltrateCategoryPickerCell.h"

@interface FiltrateViewController ()<UITableViewDataSource,UITableViewDelegate,FiltratePriceAreaCellDelegate>

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) UIButton *reset_btn,*ok_btn;


@property(nonatomic,strong)NSMutableDictionary<NSString *,NSNumber*> * expanedIndexPaths;

@property(nonatomic,strong)NSMutableDictionary<NSString *,NSNumber*> * cellHeights;

@property(nonatomic,strong)NSMutableDictionary<NSString *,NSArray*> * selectedCategorys;

@property(nonatomic,strong)NSMutableDictionary<NSString *,NSString*> * selectedTitles;

@property(nonatomic,strong)NSMutableDictionary<NSString *,NSIndexPath*> * selectedIndexPath;

@property(nonatomic,strong)NSMutableDictionary<NSString*,NSNumber*>*priceArea;


@property(nonatomic,strong)NSArray * dataSource;
@end

@implementation FiltrateViewController
-(NSMutableDictionary<NSString *,NSNumber *> *)expanedIndexPaths{
    if (!_expanedIndexPaths) {
        _expanedIndexPaths = [NSMutableDictionary dictionary];
    }
    return _expanedIndexPaths;
}


-(NSMutableDictionary<NSString *,NSNumber *> *)cellHeights{
    if (!_cellHeights) {
        _cellHeights = [NSMutableDictionary dictionary];
    }
    return _cellHeights;
}

-(NSMutableDictionary<NSString *,NSArray *> *)selectedCategorys{
    if (!_selectedCategorys) {
        _selectedCategorys = [NSMutableDictionary dictionary];
    }
    return _selectedCategorys;
}

-(NSMutableDictionary<NSString *,NSString *> *)selectedTitles{
    if (!_selectedTitles ) {
        _selectedTitles = [NSMutableDictionary dictionary];
    }
    return _selectedTitles;
}

-(NSMutableDictionary<NSString *,NSIndexPath *> *)selectedIndexPath{
    if (!_selectedIndexPath) {
        _selectedIndexPath = [NSMutableDictionary dictionary];
    }
    return _selectedIndexPath;
}

-(NSMutableDictionary<NSString *,NSNumber *> *)priceArea{
    if (!_priceArea) {
        _priceArea = [NSMutableDictionary dictionary];
    }
    return _priceArea;
}



- (void)viewDidLoad {
    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(FiltrateCategoryPickerCellNoti:) name:ChangeExpandNotificationKey object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(FiltrateCategoryPickerCellNoti:) name:SelectedCategoryNotificationKey object:nil];

    self.preferredContentSize = CGSizeMake(SCREEN_WIDTH-autoScaleW(40), SCREENH_HEIGHT);
    self.automaticallyAdjustsScrollViewInsets = NO;

    [self createTableView];
    [self createButton];
}
-(void)createButton{

    WeakSelf(weakSelf);


    UIView *lineView = [[UIView alloc] initWithFrame:CGRectZero];
    lineView.backgroundColor = View_BackgroundColor;
    [self.view addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {

        make.top.mas_equalTo(weakSelf.tableView.mas_bottom).offset(0);
        make.left.mas_equalTo(0);
        make.width.mas_equalTo(weakSelf.tableView.frame.size.width);
        make.height.mas_equalTo(autoScaleH(0.5));

    }];

    _reset_btn = [HMButton createButtonWithTitle:@"重置" andTitleColor:RGBA(156,156,156,1) andBgColor:[UIColor whiteColor] andImage:nil andBgImage:nil andSelecter:@selector(clickButton:) andTarget:self andTag:101];

    [self.view addSubview:_reset_btn];

    [_reset_btn mas_makeConstraints:^(MASConstraintMaker *make) {

            make.top.mas_equalTo(weakSelf.tableView.mas_bottom).offset(autoScaleH(0.5));
        make.left.mas_equalTo(0);
       make.width.mas_equalTo(weakSelf.tableView.frame.size.width/2);
        make.height.mas_equalTo(autoScaleH(40));
        
    }];

    _ok_btn = [HMButton createButtonWithTitle:@"确定" andTitleColor:[UIColor whiteColor] andBgColor:RGBA(78,159,242,1) andImage:nil andBgImage:nil andSelecter:@selector(clickButton:) andTarget:self andTag:102];

    [self.view addSubview:_ok_btn];

    [_ok_btn mas_makeConstraints:^(MASConstraintMaker *make) {

        make.top.mas_equalTo(weakSelf.tableView.mas_bottom).offset(autoScaleH(0.5));
        make.right.mas_equalTo(0);
        make.width.mas_equalTo(weakSelf.tableView.frame.size.width/2);
        make.height.mas_equalTo(autoScaleH(40));
        
    }];



}

-(void)clickButton:(UIButton *)button{

    switch (button.tag) {
        case 101:
        {
            [self.expanedIndexPaths removeAllObjects];
            [self.cellHeights removeAllObjects];
            [self.selectedCategorys removeAllObjects];
            [self.tableView reloadData];

            if (self.delegate&&[self.delegate respondsToSelector:@selector(FiltrateViewController:didClickResetButton:)]) {
                [self.delegate FiltrateViewController:self didClickResetButton:button];
            }

        }
            break;

        case 102:
        {
            if (self.delegate && [self.delegate respondsToSelector:@selector(FiltrateViewController:didClickOkButton:withSelectedCategorys:)]) {

                NSMutableArray * arr = [NSMutableArray array];

                //遍历  字典
                for (NSIndexPath * indexPath in self.selectedIndexPath.allValues) {
                    NSString * title = self.selectedTitles[[self stringFrom:indexPath]];
                    NSArray * categorys = self.selectedCategorys[[self stringFrom:indexPath]];
                    [arr addObject:@{@"title":title,@"categorys":categorys}];
                }

                [self.delegate FiltrateViewController:self didClickOkButton:button withSelectedCategorys:@{@"categorys":arr,@"price":self.priceArea}];
            }

        }
            break;

        default:
            break;
    }

}

-(void)createTableView{



    _tableView =[[UITableView alloc]initWithFrame:CGRectMake(0, 20, autoScaleW(330), GET_FRAME_HEIGHT(self.view)-autoScaleH(40.5) - 20) style:UITableViewStylePlain];

    _tableView.delegate = self;
    _tableView.dataSource = self;

    _tableView.rowHeight = autoScaleH(90);

    [self.view addSubview:_tableView];

    [_tableView registerClass:[FiltratePriceAreaCell class] forCellReuseIdentifier:@"FiltratePriceAreaCell"];

    [_tableView registerClass:[FiltrateCategoryPickerCell class] forCellReuseIdentifier:@"FiltrateCategoryPickerCell"];

    
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:ChangeExpandNotificationKey object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SelectedCategoryNotificationKey object:nil];
}

-(void)FiltrateCategoryPickerCellNoti:(NSNotification*)noti{
    if ([noti.name isEqualToString:ChangeExpandNotificationKey]) {
        NSIndexPath * indexPath = noti.object;


       //NSInteger maxDisplayCount = [self.dataSource[indexPath.section-1][@"maxDisplayCount"] integerValue];

        BOOL expaned = [noti.userInfo[FiltrateCategoryPickerCellExpandSatusKey] boolValue];
        self.expanedIndexPaths[[self stringFrom:indexPath]] = @(expaned);
        NSArray * arr =  noti.userInfo[FiltrateCategoryPickerCellCategorysKey];
        if (expaned) {
            NSInteger rows = arr.count/3;
            if (arr.count%3 != 0) {
                rows++;
            }
            self.cellHeights[[self stringFrom:indexPath]] = @(autoScaleH(40)+(rows)*(autoScaleH(26)+autoScaleH(10))+autoScaleH(10));
        }else{
            CGFloat h = autoScaleH(40)+autoScaleH(20);
            if (arr.count>0) {
                h+=autoScaleH(26);
            }
            self.cellHeights[[self stringFrom:indexPath]] = @(h);
        }
        [self.tableView reloadData];

    }
    if ([noti.name isEqualToString:SelectedCategoryNotificationKey]) {

        NSIndexPath * indexPath = noti.object;
        NSString * title = noti.userInfo[FiltrateSelectedTitleKey];
        NSArray * selectedCategorys = noti.userInfo[FiltrateSelectedCategorysKey]?noti.userInfo[FiltrateSelectedCategorysKey]:@[];

        self.selectedCategorys[[self stringFrom:indexPath]] =selectedCategorys;
        self.selectedTitles[[self stringFrom:indexPath]] = title;
        self.selectedIndexPath[[self stringFrom:indexPath]] = indexPath;

        if (selectedCategorys.count <= 0) {
            [self.selectedIndexPath removeObjectForKey:[self stringFrom:indexPath]];
        }
        [self.tableView reloadData];
    }
}

-(NSString*)stringFrom:(NSIndexPath*)indexPath{
    return [NSString stringWithFormat:@"(%ld,%ld)",indexPath.section,indexPath.row];
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1+self.dataSource.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        FiltratePriceAreaCell * cell = [tableView dequeueReusableCellWithIdentifier:@"FiltratePriceAreaCell"];
        cell.indexPath = indexPath;
        cell.delegate = self;
        cell.title = @"价格区间";
        return cell;
    }else {
        FiltrateCategoryPickerCell * cell = [tableView dequeueReusableCellWithIdentifier:@"FiltrateCategoryPickerCell"];
        cell.indexPath = indexPath;
        cell.title = self.dataSource[indexPath.section-1][@"title"];

        cell.categorys = self.dataSource[indexPath.section-1][@"categorys"];
        cell.selectedCategorys = self.selectedCategorys[[self stringFrom:indexPath]];
        cell.expaned = [self.expanedIndexPaths[[self stringFrom:indexPath]] boolValue];
        cell.maxDisplayCount = [self.dataSource[indexPath.section-1][@"maxDisplayCount"] integerValue];

        return cell;
    }
}

//-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
//    return section==0?0.1:10;
//
//
//}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{

     return 10;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 100;
    }else{
        CGFloat h = [self.cellHeights[[self stringFrom:indexPath]] floatValue];
        if (h<=0) {
            return 95;
        }else{
            return h;
        }
    }

    return 0.f;
}




-(void)FiltratePriceAreaCell:(FiltratePriceAreaCell *)cell valueChangeWithLowPriceTextFiled:(UITextField *)textField{
    self.priceArea[@"low"] = @([textField.text floatValue]);
}

-(void)FiltratePriceAreaCell:(FiltratePriceAreaCell *)cell valueChangeWithHeightPriceTextFiled:(UITextField *)textField{
    self.priceArea[@"height"] = @([textField.text floatValue]);
}

-(NSArray *)dataSource{
    if (!_dataSource) {
        _dataSource = @[
                        @{@"title":@"品牌",
                          @"maxDisplayCount":@(9),
                          @"categorys":
                              @[
                                  @{@"label":@"啊牌1",@"value":@"1"},
                                  @{@"label":@"啊牌2",@"value":@"1"},
                                  @{@"label":@"啊牌3",@"value":@"1"},
                                  @{@"label":@"啊牌4",@"value":@"1"},
                                  @{@"label":@"吧牌2",@"value":@"2"},
                                  @{@"label":@"晨牌3",@"value":@"3"},
                                  @{@"label":@"的牌4",@"value":@"4"},
                                  @{@"label":@"额牌5",@"value":@"5"},
                                  @{@"label":@"风牌6",@"value":@"6"},
                                  @{@"label":@"个牌7",@"value":@"6"},
                                  @{@"label":@"好牌8",@"value":@"6"},
                                  @{@"label":@"i牌9",@"value":@"6"},
                                  @{@"label":@"就牌10",@"value":@"6"},
                                  @{@"label":@"看牌11",@"value":@"6"},
                                  @{@"label":@"了牌12",@"value":@"6"},
                                  @{@"label":@"吗牌13",@"value":@"6"},
                                  @{@"label":@"你牌14",@"value":@"6"},
                                  @{@"label":@"哦牌15",@"value":@"6"},
                                  @{@"label":@"品牌16",@"value":@"6"},
                                  @{@"label":@"去牌17",@"value":@"6"},
                                  @{@"label":@"人牌18",@"value":@"6"},
                                  @{@"label":@"是牌19",@"value":@"6"},
                                  @{@"label":@"他牌20",@"value":@"6"},
                                  @{@"label":@"u牌21",@"value":@"6"},
                                  @{@"label":@"v牌22",@"value":@"6"},
                                  @{@"label":@"我牌23",@"value":@"6"},
                                  @{@"label":@"想牌24",@"value":@"6"},
                                  @{@"label":@"有牌25",@"value":@"6"},
                                  @{@"label":@"在牌26",@"value":@"6"},
                                  ],
                          },
                        @{@"title":@"厂家",
                          @"maxDisplayCount":@(0),
                          @"categorys":
                              @[
                                  @{@"label":@"啊牌1",@"value":@"1"},
                                  @{@"label":@"啊牌2",@"value":@"1"},
                                  @{@"label":@"啊牌3",@"value":@"1"},
                                  @{@"label":@"啊牌4",@"value":@"1"},
                                  @{@"label":@"吧牌2",@"value":@"2"},
                                  @{@"label":@"晨牌3",@"value":@"3"},
                                  @{@"label":@"的牌4",@"value":@"4"},
                                  @{@"label":@"额牌5",@"value":@"5"},
                                  @{@"label":@"风牌6",@"value":@"6"},
                                  @{@"label":@"个牌7",@"value":@"6"},
                                  @{@"label":@"好牌8",@"value":@"6"},
                                  @{@"label":@"i牌9",@"value":@"6"},
                                  @{@"label":@"就牌10",@"value":@"6"},
                                  @{@"label":@"看牌11",@"value":@"6"},
                                  @{@"label":@"了牌12",@"value":@"6"},
                                  @{@"label":@"吗牌13",@"value":@"6"},
                                  @{@"label":@"你牌14",@"value":@"6"},
                                  @{@"label":@"哦牌15",@"value":@"6"},
                                  @{@"label":@"品牌16",@"value":@"6"},
                                  @{@"label":@"去牌17",@"value":@"6"},
                                  @{@"label":@"人牌18",@"value":@"6"},
                                  @{@"label":@"是牌19",@"value":@"6"},
                                  @{@"label":@"他牌20",@"value":@"6"},
                                  @{@"label":@"u牌21",@"value":@"6"},
                                  @{@"label":@"v牌22",@"value":@"6"},
                                  @{@"label":@"我牌23",@"value":@"6"},
                                  @{@"label":@"想牌24",@"value":@"6"},
                                  @{@"label":@"有牌25",@"value":@"6"},
                                  @{@"label":@"在牌26",@"value":@"6"},
                                  ],
                          },
                        ];
    }
    return _dataSource;
}

+(WEPopoverController *)pop{
    return [self popWithDelegate:nil];
}

+(WEPopoverController *)popWithDelegate:(id<FiltrateViewControllerDelegate>)delegate{

    return [self popWithDelegate:delegate completion:nil];
}

+(WEPopoverController *)popWithDelegate:(id<FiltrateViewControllerDelegate>)delegate completion:(void (^)())completion{


    FiltrateViewController * fvc =  [[FiltrateViewController alloc]init];

    fvc.delegate = delegate;
    WEPopoverController * pop = [[WEPopoverController alloc]
                                 initWithContentViewController:fvc];
    pop.backgroundColor = RGBA(0, 0, 0, 0.5);
    pop.animationType = WEPopoverAnimationTypeSlide;

    pop.popoverLayoutMargins = UIEdgeInsetsMake(-20, 0, 0, 0);
    pop.containerViewProperties = [WEPopoverController defaultContainerViewProperties];
    pop.containerViewProperties.contentMargins = UIEdgeInsetsZero;
    pop.containerViewProperties.backgroundMargins = UIEdgeInsetsZero;

    [pop presentPopoverFromRect:CGRectMake(SCREEN_WIDTH, 0, SCREEN_WIDTH, SCREENH_HEIGHT) inView:[UIApplication sharedApplication].keyWindow permittedArrowDirections:UIPopoverArrowDirectionRight animated:YES completion:completion];

    return pop;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
